<template>
  <div class="chat-container">
    <!-- Right side: Chat box -->
    <div class="right-side">
      <!-- Chat header -->
      <div class="chat-header">
        <span>{{ loginUser.userName }}</span>
      </div>
      <!-- Chat messages -->
      <el-scrollbar class="chat-messages" ref="messageContainer">
        <div class="messageBox" v-for="message in messages">
          <div><img :src="logo" alt="" style="border: 1px solid #70c1fa;"></div>
          <div class="messageContent" v-if="message.isAssistant=='0'">
            {{ message.content }}
          </div>
          <div class="markdown-body" v-else  v-html="message.content">

          </div>
          <div class="messageTime"></div>
        </div>
      </el-scrollbar>
      <div class="chat-input">
        <el-input v-model="newMessage.content" placeholder="请输入聊天内容" autosize class="message-input"
                  @keydown.enter.native="sendMessage"></el-input>
        <el-button type="primary" @click.native="sendMessage" class="send-button">发送</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {saveAIChat} from '@/api/AIChat/AIChat'
import logo from '@/assets/logo/logo.jpg'
import Footer from "@/views/tool/build/Footer.vue";
import Header from "@/views/tool/build/Header.vue";
import moment from "moment/moment";
import marked  from 'marked';

export default {
  components: {Footer, Header},
  data() {
    return {
      chatId: '',
      baseURL: process.env.VUE_APP_BASE_API,
      numbers: 0,
      eventSource: null,
      logo,
      loginUser: {
        userId: "",
        userName: "",

      },
      messages: [],
      messageForm: [], // 聊天所有信息
      newMessage: {
        handle: '',
        sendUser: '',
        receiveUser: '',
        content: '',
        is_read: '0',
        createTime: ''
      },
      sourceCode:'',  // ai回答的原文本
    }
  },
  methods: {
    sendMessage() {

      if (!this.newMessage.content.trim()) {
        this.$message.warning('请输入聊天内容')
        return
      }
      this.numbers++;
      var  myMessage = this.newMessage.content
      this.newMessage.content = "";
      this.messages.push({
        content: myMessage,
        createTime: moment(new Date()).format("YYYY-MM-DD HH:mm:ss") ,
        isAssistant:'0'
      })
      this.connectToSSE(myMessage)
    },


    // 消息过多的时候滚动到最新消息位置
    scrollToBottom() {
      // 使用 $refs 来获取对消息容器的引用
      const container = this.$refs.messageContainer.$refs.wrap
      // 滚动到底部
      container.scrollTop = container.scrollHeight
    },

    getChatInfoList() {
      this.listLoading = true
      this.messageForm.chatId = this.chatId
      list(this.messageForm).then(response => {
        console.log(response)
        this.messages = response.data.records
        this.listLoading = false

      })
    },

    saveAIChat(userId){
      if (this.chatId== ''){
        saveAIChat(userId).then(res => {
          if (res.code == 200) {
            this.chatId = res.chatId
          }
        })
      }
    },

    connectToSSE(myMessage) {
      this.sourceCode = '';
      this.messages.push({
        content: '',
        createTime: '',
        isAssistant: '1',
      })
      // 构建带有查询参数的 URL
      var userId = this.loginUser.userId ;
      var url = this.baseURL + "/web/AIChat/stream?userid=" + userId + "&content=" + myMessage +"&chatId="  + this.chatId
      this.eventSource = new EventSource(url);
      this.eventSource.onmessage = (event) => {
        const data = JSON.parse(event.data) //将字符串转换成json格式
        if (data.output.choices[0].finish_reason != "stop") { //判断结束标识
          this.sourceCode += data.output.choices[0].message.content;
          this.messages[this.numbers].content = marked(this.sourceCode)
        } else {
          this.eventSource.close();
          this.numbers ++;
        }
        // 将聊天记录总下拉到最下方
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      };
      this.eventSource.onerror = (error) => {
        if (this.eventSource.readyState === EventSource.CLOSED) {
          console.log('Connection to server closed');
        } else {
          console.error('Error occurred:', error);
        }
      };
    },
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  mounted() {

  },
  created() {
    this.$store.dispatch('GetInfo')
    this.loginUser.userId = this.$store.state.user.id
    this.loginUser.userName = this.$store.state.user.name
    this.saveAIChat(this.loginUser.userId)
    // this.connectToSSE();
  },

}
</script>

<style scoped>

.chat-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(to bottom right, #FFFFFF, #ECEFF1);
}

.right-side {
  flex: 3;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
  font-size: 1.2em;
  color: #37474F;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.chat-input {
  padding: 20px;
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  margin-right: 10px;
}

.send-button {
  flex-shrink: 0;
}


.messageBox {
  display: flex;
  align-items: flex-start; /* 将头像和文本第一行对齐 */
  margin-bottom: 10px;
}

.messageBox img {
  width: 40px; /* 调整头像大小 */
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  margin-left: 10px;
}

.messageContent {
  max-width: 70%; /* 调整发送信息宽度 */
  padding: 10px;
  border-radius: 8px;
  background-color: #f0f0f0;
  text-align: left; /* 文本左对齐 */
  word-wrap: break-word; /* 当文本过长时自动换行 */
}

.messageTime {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
  margin-top: 5px; /* 将发送时间与文本分隔开 */
}

.ownMessage {
  flex-direction: row-reverse;
  align-items: flex-end; /* 将发送时间放置在最下方的贴右位置 */
}

.otherMessage {
  flex-direction: row;
  align-items: flex-end; /* 将发送时间放置在最下方的贴左位置 */
}

.online-dot {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 10px;
  height: 10px;
  background-color: #01c201;
  border-radius: 50%;
}

.message-badge .el-badge__content {
  position: absolute;
  bottom: 5px; /* Adjust to your desired position */
  left: 5px; /* Adjust to your desired position */
  background-color: #f56c6c; /* Red background for visibility */
  color: white; /* White text color */
}
</style>

